<template>
  <div class="study-room-list">
    <div class="container">
      <div class="page-header">
        <h1>自习室列表</h1>
        <el-button type="primary" size="large" @click="createRoom">
          <el-icon><Plus /></el-icon>
          创建自习室
        </el-button>
      </div>

      <div class="filter-section">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="公开自习室" name="public">
            <div class="filter-bar">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索自习室..."
                class="search-input"
                :prefix-icon="Search"
                @input="handleSearch"
              />
              <el-select
                v-model="sortBy"
                placeholder="排序方式"
                @change="handleSort"
              >
                <el-option label="最新创建" value="newest" />
                <el-option label="参与人数" value="participants" />
                <el-option label="活跃度" value="activity" />
              </el-select>
              <el-select
                v-model="categoryFilter"
                placeholder="筛选分类"
                @change="handleFilter"
              >
                <el-option label="全部" value="" />
                <el-option label="考研" value="考研" />
                <el-option label="编程" value="编程" />
                <el-option label="语言学习" value="语言学习" />
                <el-option label="其他" value="其他" />
              </el-select>
            </div>
          </el-tab-pane>

          <el-tab-pane label="好友创建的自习室" name="friends">
            <div class="friends-filter">
              <el-input
                v-model="friendsSearch"
                placeholder="搜索好友自习室..."
                class="search-input"
                :prefix-icon="Search"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="我创建的自习室" name="mine">
            <div class="filter-bar">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索自习室..."
                class="search-input"
                :prefix-icon="Search"
                @input="handleSearch"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="私密自习室" name="private">
            <div class="private-join">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索自习室..."
                class="search-input"
                :prefix-icon="Search"
                @input="handleSearch"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 自习室列表 -->
      <div class="rooms-grid" v-loading="loading">
        <div v-for="room in filteredRooms" :key="room.roomId" class="room-card">
          <div class="room-header">
            <!-- 标题 -->
            <div class="room-title">
              <h3>{{ room.roomName }}</h3>
              <el-tag :type="getRoomTypeTag(room.openness)" size="small">
                {{ getRoomTypeText(room.openness) }}
              </el-tag>
            </div>
            <!-- 房间状态 -->
            <div class="room-status">
              <el-icon v-if="room.isActive" color="#67c23a"
                ><VideoPlay
              /></el-icon>
              <el-icon v-else color="#909399"><VideoPause /></el-icon>
            </div>
          </div>
          <!-- 描述 -->
          <p class="room-description">{{ room.description }}</p>
          <div class="room-info">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>{{ room.memberCount }}/{{ room.capacity }}</span>
            </div>
            <div class="info-item">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(room.createTime) }}</span>
            </div>
          </div>
          <div class="room-features">
            <el-tooltip content="聊天" placement="top">
              <div class="feature-item" :class="{ active: room.enableChat }">
                <el-icon><ChatDotRound /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip content="摄像头" placement="top">
              <div class="feature-item" :class="{ active: room.enableCamera }">
                <el-icon><Camera /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip content="麦克风" placement="top">
              <div class="feature-item" :class="{ active: room.enableMic }">
                <el-icon><Microphone /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip content="屏幕共享" placement="top">
              <div
                class="feature-item"
                :class="{ active: room.enableScreenShare }"
              >
                <el-icon><Monitor /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip content="笔记" placement="top">
              <div class="feature-item" :class="{ active: room.enableNote }">
                <el-icon><EditPen /></el-icon>
              </div>
            </el-tooltip>
          </div>
          <div v-if="room.openness === 'private'" class="room-password">
            <el-input
              v-model="room.password"
              placeholder="请输入房间密码"
              type="password"
              show-password
              size="small"
              @keyup.enter="joinRoom(room)"
            >
            </el-input>
          </div>
          <div class="room-actions">
            <el-button
              type="primary"
              :disabled="room.memberCount >= room.capacity"
              @click="joinRoom(room)"
            >
              {{ room.memberCount >= room.capacity ? "房间已满" : "加入" }}
            </el-button>
            <!-- <el-button @click="viewRoomDetail(room)">详情</el-button> -->
          </div>
        </div>
      </div>

      <div v-if="filteredRooms.length === 0" class="empty-state">
        <el-icon size="60" color="#c0c4cc"><House /></el-icon>
        <p>暂无自习室</p>
        <el-button type="primary" @click="createRoom"
          >创建第一个自习室</el-button
        >
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalRooms"
          layout="prev, pager, next, total"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStudyRoomStore } from "@/stores";
import {
  Plus,
  Search,
  User,
  Clock,
  View,
  VideoPlay,
  VideoPause,
  House,
} from "@element-plus/icons-vue";
import type { StudyRoom } from "@/stores";
import { getRoomList, verifyPwd } from "@/api/room";
import { getMyFriends } from "@/api/social";
import { useUserStore } from "@/stores";
import { ElMessage, ElMessageBox } from "element-plus";
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const studyRoomStore = useStudyRoomStore();
const activeTab = ref("public");
const loading = ref(false);
const searchKeyword = ref("");
const friendsSearch = ref("");
const roomId = ref("");
const sortBy = ref("newest");
const categoryFilter = ref("");
const currentPage = ref(1);
const pageSize = ref(12);
const allRooms = ref<StudyRoom[]>([]);
//获取好友列表用于筛选好友的自习室
const friendList = ref();
const fetchFriends = async () => {
  try {
    friendList.value = await getMyFriends(userStore.currentUser.userId);
  } catch (error) {
    ElMessage.error("获取好友列表失败，请尝试刷新页面");
    console.error(error);
  }
};

// 房间列表过滤器
const filteredRooms = computed(() => {
  let rooms = allRooms.value;
  if (activeTab.value === "public") {
    rooms = rooms.filter((room) => room.openness === "public");
    if (searchKeyword.value) {
      rooms = rooms.filter(
        (room) =>
          room.roomName
            .toLowerCase()
            .includes(searchKeyword.value.toLowerCase()) ||
          room.description
            .toLowerCase()
            .includes(searchKeyword.value.toLowerCase())
      );
    }
    if (categoryFilter.value) {
      rooms = rooms.filter(
        (room) =>
          room.roomName.includes(categoryFilter.value) ||
          room.description.includes(categoryFilter.value)
      );
    }
  } else if (activeTab.value === "friends") {
    if (friendList.value) {
      const friendUserIds = friendList.value.map(
        (friend: any) => friend.userId
      );
      rooms = rooms.filter((room) => friendUserIds.includes(room.creator));
    } else {
      rooms = null;
    }

    if (friendsSearch.value) {
      rooms = rooms.filter((room) =>
        room.roomName.toLowerCase().includes(friendsSearch.value.toLowerCase())
      );
    }
  } else if (activeTab.value === "private") {
    rooms = rooms.filter((room) => room.openness === "private");

    if (friendsSearch.value) {
      rooms = rooms.filter((room) =>
        room.roomName.toLowerCase().includes(friendsSearch.value.toLowerCase())
      );
    }
  } else if (activeTab.value === "mine") {
    rooms = rooms.filter(
      (room) => room.creator == userStore.currentUser.userId.toString()
    );
    if (searchKeyword.value) {
      rooms = rooms.filter(
        (room) =>
          room.roomName
            .toLowerCase()
            .includes(searchKeyword.value.toLowerCase()) ||
          room.description
            .toLowerCase()
            .includes(searchKeyword.value.toLowerCase())
      );
    }
  }

  return rooms;
});

const totalRooms = computed(() => filteredRooms.value.length);

onMounted(() => {
  handleInit();
});

const handleInit = async () => {
  await fetchFriends();
  await loadRooms();
  handleInvite();
};

const handleInvite = () => {
  if (!route) {
    return;
  }
  const roomId = route.query.roomId;
  const password = route.query.password;
  if (!roomId) {
    return;
  } else if (password) {
    verifyPwd(roomId.toString(), password.toString()).then((res) => {
      if (res.data) {
        console.log(res.data);
        joinRoom(res.data);
      } else {
        ElMessage.error("分享链接有误，请重试");
      }
    });
  } else {
    verifyPwd(roomId.toString(), "").then((res) => {
      if (res.data) {
        console.log(res.data);
        joinRoom(res.data);
      } else {
        ElMessage.error("邀请链接失效，请重试");
      }
    });
  }
};

const loadRooms = async () => {
  loading.value = true;
  await getRoomList()
    .then((res) => {
      allRooms.value = res.data;
      console.log(allRooms.value);
    })
    .catch((err) => {
      console.log(`error: room list load failed, err: ${err}`);
    });
  loading.value = false;
};

const handleTabClick = (tab: any) => {
  activeTab.value = tab.props.name;
  currentPage.value = 1;
};

const handleSearch = () => {
  currentPage.value = 1;
};

const handleSort = () => {
  // 实现排序逻辑
};

const handleFilter = () => {
  currentPage.value = 1;
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const getRoomTypeTag = (openness: string) => {
  const typeMap: Record<string, string> = {
    public: "",
    friends: "success",
    private: "info",
  };
  return typeMap[openness] || "";
};

const getRoomTypeText = (openness: string) => {
  const typeMap: Record<string, string> = {
    public: "公开",
    friends: "好友",
    private: "私密",
  };
  return typeMap[openness] || "公开";
};

const formatTime = (timeStr: string) => {
  const now = new Date();
  const time = new Date(timeStr);
  const diff = now.getTime() - time.getTime();
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

  if (hours > 0) {
    return `${hours}小时前`;
  }
  return `${minutes}分钟前`;
};

const createRoom = () => {
  router.push("/study-room/create");
};

const joinRoom = (room: StudyRoom) => {
  if (
    studyRoomStore.currentRoom &&
    room.roomId !== studyRoomStore.currentRoom.roomId
  ) {
    ElMessageBox.confirm(
      `你已经加入*${studyRoomStore.currentRoom.roomName}*房间，是否要切换房间？`,
      "Warning",
      {
        confirmButtonText: "确定",
        cancelButtonText: "不了",
        type: "warning",
      }
    ).then(() => {
      ElMessage.warning("切换房间中...");
      studyRoomStore.leaveRoom();
      setTimeout(() => {
        studyRoomStore.joinRoom(room);
      }, 1000);
    });
  } else if (
    studyRoomStore.currentRoom &&
    room.roomId === studyRoomStore.currentRoom.roomId
  ) {
    ElMessage.success("你已经在这个房间中了");
  } else {
    studyRoomStore.joinRoom(room);
  }
};

const viewRoomDetail = (room: StudyRoom) => {
  router.push(`/study-room/${room.roomId}`);
};
</script>

<style scoped>
.study-room-list {
  overflow-y: scroll;
  height: 100%;
  width: 100%;
}

.container {
  height: 93vh;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
  font-size: 2.5rem;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-bar {
  display: flex;
  gap: 16px;
  margin-top: 20px;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.friends-filter,
.private-join {
  margin-top: 20px;
  display: flex;
  gap: 16px;
  align-items: center;
}

.room-id-input {
  width: 200px;
}

.rooms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.room-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.room-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.room-title {
  flex: 1;
}

.room-title h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.room-description {
  color: #7f8c8d;
  line-height: 1.5;
  margin-bottom: 16px;
}

.room-info {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

.room-settings {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.room-actions {
  display: flex;
  margin-top: 16px;
  gap: 12px;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state p {
  margin: 20px 0;
  font-size: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

@media (max-width: 768px) {
  .rooms-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }

  .filter-bar {
    flex-direction: column;
  }

  .search-input {
    max-width: none;
  }
}
.room-features {
  display: flex;
  gap: 12px;
}

.feature-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f5f5f5;
  color: #909399;
  transition: all 0.3s;
}

.feature-item.active {
  background-color: #ecfff0;
  color: #67c23a;
}

.feature-item.active:hover {
  background-color: #67c23a;
  color: white;
}
.room-password {
  margin-top: 16px;
  margin-bottom: 24px;
}
</style>
